//
//  SbVC.swift
//  Auscultation
//
//  Created by 来 on 2020/11/28.
//

import UIKit
import AudioToolbox
import AVFoundation
import CoreBluetooth

class SbVC: BaseVC {
    
    var back_view1: UIView!
    var back_view2: UIView!
    
    var sbbh: UILabel!
    
    var onOff: UIView!
    var onLine: UILabel!
    
    var tb_timer: Timer?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.autoBluetooth(EWEBluetooth.lgf.isOffLine)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.autoBluetooth(EWEBluetooth.lgf.isOffLine)
    }
    
    deinit {
        EWEBluetooth.lgf.tctzyd()
        EWEBluetooth.lgf.finishScan()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        // 蓝牙初始化
        EWEBluetooth.lgf.initBluetooth()
        
        NotificationCenter.default.addObserver(self, selector: #selector(onOffLine(_:)), name: NSNotification.Name(rawValue: "ON_OFF_LINE"), object: nil)
        
        tb_timer = Timer.lgf_RunTimer(self, S: 50) { (timer) in
            EWEBluetooth.lgf.tbxt()
        }
    }
    
    override func leftBtnSelect() {
        super.leftBtnSelect()
        tb_timer?.lgf_StopTimer()
        tb_timer = nil
    }
    
    // 添加蓝牙设备
    @objc func s_tjsb(_ sender: UITapGestureRecognizer) {
        SblbV.init().show(self.view)
    }
    
    // 听诊引导模式
    @objc func goTzydms() {
        self.navigationController?.show(TzydmsVC(), sender: self)
    }
    
    // 心音采集
    @objc func goXyybcj() {
        self.navigationController?.show(XycjVC(), sender: self)
    }
    
    // 设备文件
    @objc func goSbwjhq() {
        self.navigationController?.show(SbwjlbVC(), sender: self)
    }
    
    func autoBluetooth(_ isOffLine: Bool) {
        self.back_view1.isHidden = !isOffLine
        self.onOff.backgroundColor = !isOffLine ? UIColor.green : UIColor.red
        self.onLine.text = !isOffLine ? "在线" : "离线"
        if !isOffLine {
            self.sbbh.text = EWEBluetooth.lgf.selectPeripheral?.identifier.uuidString ?? "未知"
            Timer.lgf_After(S: 0.5) { [weak self] in
                self?.gxsj()
            }
        }

    }
    
    // 更新设备时间
    func gxsj() {
        let time_name_16_left = "B107" + Date().lgf_TimeStr("YYYYMMddhhmmss")
        var ff = 0
        getStrCountArray(time_name_16_left, 2).forEach { (str) in
            ff += changeToInt(str)
        }
        let cs = String(ff % 256, radix:16)
        let time_name_all = time_name_16_left + cs + "00"
        EWEBluetooth.lgf.gxsj(time_name_all)
    }
    
    @objc func onOffLine(_ noti: Notification) {
        if let isOffLine = noti.object as? Bool {
            self.autoBluetooth(isOffLine)
        }
    }
    
}
